/*
 * @Author: xiehangyun 
 * @Date: 2025-02-21 16:34:07 
 * @Last Modified by: xiehangyun
 * @Last Modified time: 2025-02-22 10:56:52
 */

import editorStore from "@/editorComponent/editorStore";
import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./graffiti.module.less";
import graffitiEditor from "./graffitiEditor";
import graffitiStore from "./graffitiStore";
import GraffitiTools from "./GraffitiTools/GraffitiTools";

interface Iprops {
  children?: ReactNode
}

// 涂鸦组件
export default function Graffiti() {

  const rootDom = useRef<HTMLDivElement | null>(null);
  const lowerCanvasDom = useRef<HTMLCanvasElement | null>(null);
  const upperCanvasDom = useRef<HTMLCanvasElement | null>(null);
  const [graffiti, setGraffiti] = useState(editorStore.graffiti);

  useEffect(() => autorun(async () => {
    const { graffiti } = editorStore;
    setGraffiti(graffiti);
    if (graffiti) {
      await new Promise(resolve => requestAnimationFrame(resolve));
      await new Promise(resolve => requestAnimationFrame(resolve));
      await new Promise(resolve => requestAnimationFrame(resolve));
      if (rootDom.current) {
        rootDom.current.style.transform = `translate(calc(-50%),  calc( -50% + 56px) ) scale(${editorStore.scale / 100})`;
      }
      if (lowerCanvasDom.current && upperCanvasDom.current) {
        graffitiEditor.init(lowerCanvasDom.current, upperCanvasDom.current);
      }
    }
  }, { delay: 30 }), []);

  useEffect(() => autorun(() => {
    const { brushSize, brushColor, brushType } = graffitiStore;
    graffitiEditor.brushSize = brushSize;
    graffitiEditor.brushColor = brushColor;
    graffitiEditor.brushType = brushType;
  }, { delay: 30 }), []);

  return (
    graffiti ? (
      <div
        ref={rootDom}
        className={styles.graffiti}
      >
        {/* 涂鸦工具栏 */}
        <GraffitiTools />
        <canvas
          width={1024}
          height={1024}
          ref={lowerCanvasDom}
          className={styles.lowerCanvas}
        />
        <canvas
          width={1024}
          height={1024}
          ref={upperCanvasDom}
          className={styles.upperCanvas}
        />
      </div>) : null
  );
}